import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;


public class Consumer implements Runnable {
        private final Restaurant restaurant;
        private final int id;
        private Order order;
        private Random random = new Random();

        public Consumer(Restaurant restaurant, int id) {
                super();
                this.restaurant = restaurant;
                this.id = id;
        }

        @Override
        public void run() {
                while (!Thread.interrupted()) {
                        makeOrder();
                        synchronized (this) {
                                try {
                                        wait();
                                } catch (InterruptedException e) {
                                        return;
                                }
                        }
                        Logger.logWrite("" + new Date() + " " + this
                                        + " received ready order " + order.getId() + "\n");
                        try {
                                TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
                        } catch (InterruptedException e) {
                                return;
                        }
                }

        }

        private synchronized void makeOrder() {
                order = new Order(this);
                Logger.logWrite("" + new Date() + " " + this + " created new order "
                                + order.getId() + "\n");
                restaurant.takeOrder(order);
        }

        @Override
        public synchronized String toString() {
                return "Consumer " + id;
        }

}